package cn.xhy.material.service.commodityinfo;

import cn.hutool.core.bean.BeanUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.xhy.material.controller.admin.commodityinfo.vo.CommodityInfoPageReqVO;
import cn.xhy.material.controller.admin.commodityinfo.vo.CommodityInfoRespVO;
import cn.xhy.material.controller.admin.commodityinfo.vo.CommodityInfoSaveReqVO;
import cn.xhy.material.dal.dataobject.brand.BrandDO;
import cn.xhy.material.dal.dataobject.category.CategoryDO;
import cn.xhy.material.dal.dataobject.commodityinfo.CommodityInfoDO;
import cn.xhy.material.dal.dataobject.model.ModelDO;
import cn.xhy.material.dal.dataobject.producttype.ProductTypeDO;
import cn.xhy.material.dal.dataobject.specifications.SpecificationsDO;
import cn.xhy.material.dal.mysql.commodityinfo.CommodityInfoMapper;
import cn.xhy.material.service.brand.BrandService;
import cn.xhy.material.service.category.CategoryService;
import cn.xhy.material.service.model.ModelService;
import cn.xhy.material.service.producttype.ProductTypeService;
import cn.xhy.material.service.specifications.SpecificationsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.xhy.material.enums.ErrorCodeConstants.COMMODITY_INFO_NOT_EXISTS;

/**
 * 商品信息 Service 实现类
 *
 * @author xhy
 */
@Service
@Validated
public class CommodityInfoServiceImpl implements CommodityInfoService {

    @Resource
    private CommodityInfoMapper commodityInfoMapper;

    @Resource
    private SpecificationsService specificationsService;
    @Resource
    private BrandService brandService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private ProductTypeService ProductTypeService;
    @Resource
    private ModelService modelService;


    @Override
    public Long createCommodityInfo(CommodityInfoSaveReqVO createReqVO) {
        // 插入
        CommodityInfoDO commodityInfo = BeanUtils.toBean(createReqVO, CommodityInfoDO.class);
        commodityInfoMapper.insert(commodityInfo);
        // 返回
        return commodityInfo.getId();
    }

    @Override
    public void updateCommodityInfo(CommodityInfoSaveReqVO updateReqVO) {
        // 校验存在
        validateCommodityInfoExists(updateReqVO.getId());
        // 更新
        CommodityInfoDO updateObj = BeanUtils.toBean(updateReqVO, CommodityInfoDO.class);
        commodityInfoMapper.updateById(updateObj);
    }

    @Override
    public void deleteCommodityInfo(Long id) {
        // 校验存在
        validateCommodityInfoExists(id);
        // 删除
        commodityInfoMapper.deleteById(id);
    }

    private void validateCommodityInfoExists(Long id) {
        if (commodityInfoMapper.selectById(id) == null) {
            throw exception(COMMODITY_INFO_NOT_EXISTS);
        }
    }

    @Override
    public CommodityInfoDO getCommodityInfo(Long id) {
        return commodityInfoMapper.selectById(id);
    }

    @Override
    public PageResult<CommodityInfoDO> getCommodityInfoPage(CommodityInfoPageReqVO pageReqVO) {
        PageResult<CommodityInfoDO> commodityInfoDOPageResult = commodityInfoMapper.selectPage(pageReqVO);
        return commodityInfoDOPageResult;
    }


    public PageResult<CommodityInfoRespVO> getCommodityInfoPageList(CommodityInfoPageReqVO pageReqVO) {
        PageResult<CommodityInfoDO> commodityInfoDOPageResult = commodityInfoMapper.selectPage(pageReqVO, new LambdaQueryWrapper<CommodityInfoDO>()
                .eq(StringUtils.isNotBlank(pageReqVO.getType()), CommodityInfoDO::getType, pageReqVO.getType())
                .and(StringUtils.isNotBlank(pageReqVO.getBarCode()) || StringUtils.isNotBlank(pageReqVO.getGname()), commodityInfoDOLambdaQueryWrapper -> commodityInfoDOLambdaQueryWrapper
                        .eq(StringUtils.isNotBlank(pageReqVO.getBarCode()), CommodityInfoDO::getBarCode, pageReqVO.getBarCode()).like(StringUtils.isNotBlank(pageReqVO.getGname()), CommodityInfoDO::getGname, pageReqVO.getGname())));
        List<CommodityInfoRespVO> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(commodityInfoDOPageResult.getList())) {
            for (CommodityInfoDO item : commodityInfoDOPageResult.getList()) {
                CommodityInfoRespVO commodityInfoRespVO = new CommodityInfoRespVO();
                BeanUtil.copyProperties(item, commodityInfoRespVO);
                commodityInfoRespVO.setBrandName(getBrandName(item.getBrand()));
                commodityInfoRespVO.setModelName(getModelName(item.getModel()));
                commodityInfoRespVO.setCategoryName(getCategoryName(item.getCategory()));
                commodityInfoRespVO.setProductTypeName(getProductTypeName(item.getProductType()));
                commodityInfoRespVO.setSpecifName(getSpecifName(item.getSpecif()));
                list.add(commodityInfoRespVO);
            }
        }
        return new PageResult<>(list, commodityInfoDOPageResult.getTotal());
    }

    private String getBrandName(String brandId) {
        if (StringUtils.isNotEmpty(brandId)) {
            try {
                BrandDO brand = brandService.getBrand(Long.parseLong(brandId));
                return brand != null ? brand.getBrandName() : null;
            } catch (NumberFormatException e) {
                // Handle exception (log it, etc.)
            }
        }
        return null;
    }

    private String getModelName(String modelId) {
        if (StringUtils.isNotEmpty(modelId)) {
            try {
                ModelDO model = modelService.getModel(Long.parseLong(modelId));
                return model != null ? model.getModel() : null;
            } catch (NumberFormatException e) {
                // Handle exception (log it, etc.)
            }
        }
        return null;
    }

    private String getCategoryName(String categoryId) {
        if (StringUtils.isNotEmpty(categoryId)) {
            try {
                CategoryDO category = categoryService.getCategory(Long.parseLong(categoryId));
                return category != null ? category.getName() : null;
            } catch (NumberFormatException e) {
                // Handle exception (log it, etc.)
            }
        }
        return null;
    }

    private String getProductTypeName(String productTypeId) {
        if (StringUtils.isNotEmpty(productTypeId)) {
            try {
                ProductTypeDO productType = ProductTypeService.getProductType(Long.parseLong(productTypeId));
                return productType != null ? productType.getName() : null;
            } catch (NumberFormatException e) {
                // Handle exception (log it, etc.)
            }
        }
        return null;
    }

    private String getSpecifName(String specifId) {
        if (StringUtils.isNotEmpty(specifId)) {
            try {
                SpecificationsDO specifications = specificationsService.getSpecifications(Integer.parseInt(specifId));
                return specifications != null ? specifications.getSpecif() : null;
            } catch (NumberFormatException e) {
                // Handle exception (log it, etc.)
            }
        }
        return null;
    }

}
